﻿using UnityEngine;
using System.Collections;
using System.IO;
using System;
using System.Text.RegularExpressions;

/// <summary>
/// 热更新用到的一些通用函数
/// </summary>
public class HotUpdateTools {
    /// <summary>
    /// 加载资源之后的回调函数
    /// </summary>
    /// <param name="data"></param>
    public delegate void HandleBundleCallBack(WWW data);

    /// <summary>
    /// 将byte[]转换成string
    /// </summary>
    /// <param name="characters"></param>
    /// <returns></returns>
    public static string BytesToString(byte[] mbyte)
    {
        return System.Text.Encoding.UTF8.GetString(mbyte);
    }


    /// <summary>
    /// 替换本地资源
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="data"></param>
    public static void ReplaceLocalRes(string fileName, byte[] data)
    {
        string filePath = Application.persistentDataPath + "/" + fileName;
        FileInfo info = new FileInfo(filePath);
        if(!info.Directory.Exists)
        {
            info.Directory.Create();
        }

        //Debug.Log("write path is " + filePath);
        FileStream stream = new FileStream(filePath, FileMode.Create);
        stream.Write(data, 0, data.Length);
        stream.Flush();
        stream.Close();
    }

    /// <summary>
    /// 去除www路径中开头的file://字符，用在file.exists函数中
    /// </summary>
    /// <param name="wwwpath"></param>
    /// <returns></returns>
    private static string WWWPath2FilePath(string wwwpath)
    {
        Regex r = new Regex(@"^file:/+");
        Match m = r.Match(wwwpath);
        if(m.Success)
        {
            return wwwpath.Replace(m.Value, "");
        }
        return wwwpath;
    }

    /// <summary>
    /// 读取本地版本文件信息
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static IEnumerator ClientWWWLoad(string path, HandleBundleCallBack cb)
    {
        WWW bundle = null;
        string filepath = HotUpdateCfg.LocalPersistentDataPath + path;

        if (!File.Exists(WWWPath2FilePath(filepath)))
        {
            filepath = HotUpdateCfg.LocalABBasePath + path;
        }

        bundle = new WWW(filepath);

        //bundle = WWW.LoadFromCacheOrDownload(filepath,1);

        while (!bundle.isDone)
        {
            yield return new WaitForEndOfFrame();
        }

        yield return bundle;

        if (cb != null)
            cb(bundle);
    }

    /// <summary>
    /// 下载服务器文件
    /// </summary>
    /// <param name="path"></param>
    /// <param name="dir"></param>
    /// <returns></returns>
    public static IEnumerator ServerWWWLoad(string path, HandleBundleCallBack cb)
    {
        WWW bundle = new WWW(path);
        yield return bundle;
        if (cb != null)
        {
            cb(bundle);
        }    
    }
}
